package com.itheima.health.controller;

import com.itheima.health.common.MessageConst;
import com.itheima.health.common.RedisConst;
import com.itheima.health.dto.ValidateCodeDTO;
import com.itheima.health.entity.Result;
import com.itheima.health.exception.BusinessRuntimeException;
import com.itheima.health.pojo.Member;
import com.itheima.health.service.MemberService;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.swing.*;
import java.time.LocalDate;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * 登录控制器
 */
@RestController
@RequestMapping("/mobile/login")
@Slf4j
@Api(tags = "手机端登录接口")
public class MobileLoginController {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private MemberService memberService;

    @Transactional
    @PostMapping("/smsLogin")
    public Result smsLogin(@RequestBody ValidateCodeDTO validateCodeDTO){
        //验证码是否为空
        if(validateCodeDTO.getValidateCode().equals("")){
            return new Result(false,MessageConst.TELEPHONE_VALIDATECODE_NOTNULL);
//            throw new BusinessRuntimeException(MessageConst.TELEPHONE_VALIDATECODE_NOTNULL);
        }

        //从redis中获取到手机号对应的验证码和时间毫秒值
        String s = (String) redisTemplate.opsForValue().get(validateCodeDTO.getTelephone());
        String[] timeAndCode = s.split("_");
        long start = Long.parseLong(timeAndCode[0]);
        String code = timeAndCode[1];
        //获取当前时间
        LocalDate today = LocalDate.now();
        //获取当前时间毫秒值
        long now = System.currentTimeMillis();

        //判断验证码过期时间
        long time = now - start;
        if (time>=120000){
            return new Result(false,MessageConst.VALIDATECODE_ERROR);
        }

        //判断填写的验证码是否与数据库中的验证码相同
        if (validateCodeDTO.getValidateCode().equals(code)){
            //通过手机号从数据库中查找会员信息
            Member member = memberService.getMemberByTelephone(validateCodeDTO.getTelephone());
            if (member==null){
                memberService.addMember(today,validateCodeDTO.getTelephone());
                return new Result(true,MessageConst.LOGIN_SUCCESS,code);
            }else {
                return new Result(true,MessageConst.LOGIN_SUCCESS,code);
            }
        }
        return new Result(false,MessageConst.VALIDATECODE_ERROR);
    }
}
